package org.ruoyi.common.chat.handler;

import com.alibaba.fastjson2.JSON;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.ruoyi.common.chat.request.ChatRequest;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Map;

@Slf4j
@RequiredArgsConstructor
public class CommonChatWebSocketHandler extends TextWebSocketHandler {

    private final WebSocketMessageHandler messageHandler;

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) {
        String payload = message.getPayload();
        log.info("接收到的消息: {}", payload);
        try {
            // 解析接收到的消息为 ChatRequest 对象
            ChatRequest chatRequest = JSON.parseObject(payload, ChatRequest.class);
            Map<String, Object> attributes = session.getAttributes();
            log.info("WebSocketSession attributes: {}", attributes);
            // 调用消息处理器处理聊天请求，并传入 WebSocketSession
            messageHandler.handleWebSocketChat(chatRequest, session, (response) -> {
                try {
                    if (session.isOpen()) {
                        session.sendMessage(new TextMessage(response));
                        log.info("消息已发送到 WebSocket 客户端: {}", response);
                    } else {
                        log.warn("WebSocketSession 已关闭，无法发送消息");
                    }
                } catch (Exception e) {
                    log.error("发送消息到 WebSocket 客户端失败", e);
                    try {
                        if (session.isOpen()) {
                            session.close();
                        }
                    } catch (Exception ex) {
                        log.error("关闭 WebSocketSession 失败", ex);
                    }
                }
            });
        } catch (Exception e) {
            log.error("处理 WebSocket 消息时出错", e);
            try {
                if (session.isOpen()) {
                    session.close();
                }
            } catch (Exception ex) {
                log.error("关闭 WebSocketSession 失败", ex);
            }
        }
    }
}